package com.zlyx.easy.job.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zlyx.easy.core.sql.SqlBuilder;
import com.zlyx.easy.core.sql.SqlBuilder.OpType;
import com.zlyx.easy.database.local.Page;
import com.zlyx.easy.database.local.ReturnType;
import com.zlyx.easy.job.service.IDataService;
import com.zlyx.easy.mybatis.mapper.MybatisMapper;

@Service
public class DataServiceImpl implements IDataService {

	@Autowired
	private MybatisMapper mybatisMapper;

	@Override
	public Object save(String tableName, Map<String, Object> dataMap) throws Exception {
		return mybatisMapper.insert(SqlBuilder.buildSQL(OpType.INSERT, tableName, dataMap, null));
	}

	@Override
	public Object remove(String tableName, Map<String, Object> conditionMap) throws Exception {
		return mybatisMapper.delete(SqlBuilder.likeSQL(OpType.DELETE, tableName, conditionMap));
	}

	@Override
	public Object edit(String tableName, Map<String, Object> updateMap, Map<String, Object> conditionMap)
			throws Exception {
		return mybatisMapper.update(SqlBuilder.updateSQL(tableName, updateMap, conditionMap));
	}

	@Override
	public Object getOne(String tableName, Map<String, Object> parameterMap) throws Exception {
		ReturnType.setType(Map.class);
		return mybatisMapper.selectOne(SqlBuilder.likeSQL(OpType.SELECT, tableName, parameterMap));
	}

	@Override
	public Object list(String tableName, Map<String, Object> parameterMap) throws Exception {
		ReturnType.setType(Map.class);
		return mybatisMapper.select(SqlBuilder.likeSQL(OpType.SELECT, tableName, parameterMap));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object page(String tableName, Page<Map<String, Object>> page) throws Exception {
		page = page != null ? page : new Page<Map<String, Object>>();
		ReturnType.setType(Map.class);
		page.setData(
				(List<Map<String, Object>>) mybatisMapper.page(
						SqlBuilder.likeSQL(OpType.SELECT, tableName, page.getCondition())
								+ SqlBuilder.order(page.getAscs(), page.getDescs()),
						page.getPageNum(), page.getPageSize()));
		return page;
	}

}
